package com.zerox.service.impl;

import com.mysql.cj.util.StringUtils;
import com.zerox.entity.SysDept;
import com.zerox.mapper.SysDeptMapper;
import com.zerox.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class SysDeptServiceImpl implements SysDeptService  {
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Override
    public List<SysDept> selectDeptList(SysDept dept) {
        return sysDeptMapper.selectDeptList(dept);
    }

    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDept dept : depts) {
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }

        return returnList;
    }

    @Override
    public List<SysDept> list(String deptName, Integer startIndex, Integer pageSize) {
        if(Objects.isNull(startIndex)){
            startIndex = 1;
        }
        if(Objects.isNull(pageSize)){
            pageSize = 10;
        }
        int pageIndex = (startIndex-1)*pageSize;
        return sysDeptMapper.list(deptName,pageIndex,pageSize);
    }

    @Override
    public int count(String deptName) {
        return sysDeptMapper.count(deptName);
    }

    @Override
    public int add(SysDept sysDept) {
        return sysDeptMapper.add(sysDept);
    }

    @Override
    public int delete(Integer deptId) {
        return sysDeptMapper.delete(deptId);
    }

    @Override
    public SysDept selectById(Integer deptId) {
        return sysDeptMapper.selectById(deptId);
    }

    @Override
    public int update(SysDept sysDept) {
        return sysDeptMapper.update(sysDept);
    }


    private void recursionFn(List<SysDept> list, SysDept t) {
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChil : childList) {
            if (hasChild(list,tChil)){
                recursionFn(list,tChil);
            }
        }
    }

    private List<SysDept> getChildList(List<SysDept> List, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();

        for (SysDept n : List) {

            if (n.getParentId() != null && n.getParentId() == t.getDeptId())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }


    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list,t).size()>0;
    }
}
